package cn.colins.raft.rpc.handler.chanel;


import cn.colins.raft.enity.LogIndexPull;
import cn.colins.raft.enity.LogIndexPullResult;
import cn.colins.raft.node.RaftNodeService;
import cn.colins.raft.rpc.RpcRemoteContext;
import cn.colins.raft.rpc.future.RpcWriteFuture;
import cn.colins.raft.utils.ThreadPoolUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description  日志拉取请求响应
 * @Author czl
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2023/6/12
 */
public class LogPullRequestResultHandler extends SimpleChannelInboundHandler<LogIndexPullResult> {
    private static final Logger log = LoggerFactory.getLogger(LogPullRequestResultHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
        Channel channel = context.channel();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, LogIndexPullResult rpcResponse) throws Exception {
        // 获取返回值后 同步响应请求
        ThreadPoolUtils.nettyClientAsyncPool.execute(()->{
            try{
                RpcWriteFuture requestCache = RpcRemoteContext.getRequestCache(rpcResponse.getRequestId());
                if(requestCache!=null){
                    requestCache.setResponse(rpcResponse);
                }
            }finally {
                //释放
                ReferenceCountUtil.release(rpcResponse);
            }
        });
    }
}
